package com.bayleaf.common;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;


public class EncodingUtil {
	   final static String DEFAULT_CHAR_SET="UTF-8";
	    private static byte[] hexaMap =
	        {0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x41,0x42,0x43,0x44,0x45,0x46};
	   /**
     * UTF-8로 변환시의 길이를 구한다.<br>
     * ch<0x7f : 1byte<br>
     * 0x7f<=ch<0x7ff : 2byte<br>
     * 0x7ff=<ch : 3byte<br>
     */
    protected static int getUTF8Count(char[] c) {
	    int len = c.length;
    	int count = 0;
	    for (int i = 0; i < len; i++) {
	        int ch = c[i];
	        if (ch <= 0x7f) {
		        count++;
	        } else if (ch <= 0x7ff) {
		        count += 2;
	        } else {
		        count += 3;
	        }
	    }
	    return count;
    }

    /**
     * UTF-8로 변환시의 길이를 구한다.<br>
     * ch<0x7f : 1byte<br>
     * 0x7f<=ch<0x7ff : 2byte<br>
     * 0x7ff=<ch : 3byte<br>
     */
    public static int getUTF8Count(String s) {
	    return getUTF8Count(s.toCharArray());
    }

    /**
     * String을 UTF-8 encoding한 byte[]를 구한다.<br>
     */
    public static byte[] getUTF8Bytes(String s) {
	    char[] c = s.toCharArray();
    	byte[] b = new byte[getUTF8Count(c)];
    	int off = 0;
    	int len=s.length();
    	for (int i = 0; i < len; i++) {
    	    int ch = c[i];
    	    if (ch <= 0x7f) {
    		b[off++] = (byte)ch;
    	    } else if (ch <= 0x7ff) {
    		b[off++] = (byte)((ch >> 6) | 0xc0);
    		b[off++] = (byte)((ch & 0x3f) | 0x80);
    	    } else {
    		b[off++] = (byte)((ch >> 12) | 0xe0);
    		b[off++] = (byte)(((ch >> 6) & 0x3f) | 0x80);
    		b[off++] = (byte)((ch & 0x3f) | 0x80);
    	    }
    	}
    	return b;
    }
    

	  protected static String getHexaEncoding(byte[] src) {
	    byte[] buffer=new byte[src.length*3];
	    int index=0;
	    for (int i=0;i<src.length;i++) {
	        if (src[i]==0x25) {
	            buffer[index++]=0x25;
	            buffer[index++]=0x25;
	        } else {
	            buffer[index++]=0x25;
	            buffer[index++]=hexaMap[((src[i]&0xf0)>>4)];
	            buffer[index++]=hexaMap[(src[i]&0x0f)];
	        }
	    }
	    byte[] strBytes=new byte[index];
	    System.arraycopy(buffer,0,strBytes,0,index);
	
	    return new String(strBytes);
	  }
	  
	  
	  public static String encoding(String str, String encodeFr,  String encodeTo){
		try {
		return new String(str.getBytes(encodeFr), encodeTo);
		} catch(Exception ex)   {
		return str;
		}
	 }
	
	public static String java2db(String str){
		return encoding(str, "ISO-8859-1", "KSC5601");
	}
	
	public static String db2java(String str){
		return encoding(str, "KSC5601", "ISO-8859-1");
	}

	  

}
